#import "BWUtilities.h"


// utility method that ideally should be in some common library
// or provided by Apple.
// Given two rectangles, center one inside of the other

NSRect BWCenterRectInRect (NSRect smallRect, NSRect bigRect)
{
    NSRect centerRect;
    centerRect.size = smallRect.size;

    centerRect.origin.x = (bigRect.size.width - smallRect.size.width) / 2.0;
    centerRect.origin.y = (bigRect.size.height - smallRect.size.height) / 2.0;

    return (centerRect);

} // BWCenterRectInRect



// fit a rectangle inside of another one so that it maximally fill up
// one of the dimension

typedef enum RectAxis {
    RectAxisHorizontal,
    RectAxisVertical
} RectAxis;



NSRect BWFitRectIntoDimension (NSRect inner, NSRect outer, RectAxis dimension)
{
    NSRect result;
    float proportion;

    if (dimension == RectAxisHorizontal) {
        proportion = inner.size.height / inner.size.width;
        result.size.width = outer.size.width;
        result.size.height = result.size.width * proportion;
        result.origin = inner.origin;

    } else if (dimension == RectAxisVertical) {
        proportion = inner.size.width / inner.size.height;
        result.size.height = outer.size.height;
        result.size.width = result.size.height * proportion;
        result.origin = inner.origin;

    } else {
        NSLog (@"fitRect:  bad dimension");
        result = NSZeroRect;
    }

    return (result);

} // fitRect with dimension





// how many rectangle fitting methods can we have?  at least one
// more.

NSRect BWFitRectInto (NSRect inner, NSRect outer)
{
    NSRect result;
    float innerProportion;

    innerProportion = inner.size.width / inner.size.height;

    result = inner;
    if (innerProportion > 1) {
        // wider
        result = BWFitRectIntoDimension (inner, outer, RectAxisHorizontal);
    } else {
        // taller
        result = BWFitRectIntoDimension (inner, outer, RectAxisVertical);
    }

    if (result.size.width > outer.size.width) {
        result = BWFitRectIntoDimension (inner, outer, RectAxisHorizontal);
    }
    if (result.size.height > outer.size.height) {
        result = BWFitRectIntoDimension (inner, outer, RectAxisVertical);
    }
    if (result.size.width > outer.size.width) {
        result = BWFitRectIntoDimension (inner, outer, RectAxisHorizontal);
    }

    result = BWCenterRectInRect (result, outer);

    return (result);

} // fitRect


